<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-03-14 14:06:38
 * @Description  : 用户的安全管理页面
-->
<template>
  <n-tabs
    type="line"
    animated
    :value="activeTab"
    @update:value="handleTabChange"
  >
    <n-tab-pane name="login-device" tab="登录设备">
      <wp-data-table
        v-loading="loading"
        :data="data"
        :checked-row-keys="checkedRowKeys"
        :columns="columns"
        :pages="pageResultInfo.pages"
        :total="pageResultInfo.total"
        @page-change="handlePageChange"
        @sort-change="handleSorterChange"
        :is-sort="false"
      >
      </wp-data-table>
    </n-tab-pane>
    <n-tab-pane name="login-log" tab="登录日志">
      <wp-data-table
        v-loading="loading"
        :data="data"
        :checked-row-keys="checkedRowKeys"
        :columns="columns"
        :pages="pageResultInfo.pages"
        :total="pageResultInfo.total"
        @page-change="handlePageChange"
        @sort-change="handleSorterChange"
        :is-sort="false"
      >
      </wp-data-table
    ></n-tab-pane>
    <n-tab-pane name="online-device" tab="在线设备">
      <wp-data-table
        v-loading="loading"
        :data="data"
        :checked-row-keys="checkedRowKeys"
        :columns="columns"
        :pages="pageResultInfo.pages"
        :total="pageResultInfo.total"
        @page-change="handlePageChange"
        @sort-change="handleSorterChange"
        :is-sort="false"
      >
      </wp-data-table>
    </n-tab-pane>
  </n-tabs>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { getLogDeviceByPage, getUserLogByPage } from '@/api/log'
import type { LogRowData } from '@/types/log'
import { renderIp, renderOs } from '@/utils/commonBusiness'
import { formatTime } from '@/utils/index'
import type { IndexObj } from '@/types/commom'

const activeTab = ref('login-device')

const handleTabChange = (value: string) => {
  activeTab.value = value
  initPageInfo()
  loadData()
}

// 根据tab的不同，column的列也不同
const columns = computed(() => {
  const staticColumns = [
    {
      title: '客户端',
      key: 'browser',
      minWidth: 180,
      width: 180,
      render: (row: IndexObj) => {
        return renderOs(row.uaParse.browser)
      }
    },
    {
      title: '系统',
      key: 'os',
      minWidth: 120,
      width: 120,
      render: (row: IndexObj) => {
        return renderOs(row.uaParse.os)
      }
    },
    {
      title: '登录时间',
      key: 'createTime',
      minWidth: 150,
      width: 150,
      render(row: IndexObj) {
        return formatTime(row.createTime)
      }
    },
    {
      title: '登录地址',
      key: 'ip',
      minWidth: 150,
      width: 150,
      render(row: IndexObj) {
        return renderIp(row.ip)
      }
    },
    {
      title: '操作',
      key: 'action',
      minWidth: 150,
      width: 150,
      render(row: IndexObj) {
        return h('div', [
          h(
            NButton,
            {
              text: true,
              type: 'primary',
              size: 'small',
              class: 'text-[13px]'
            },
            { default: () => '编辑' }
          )
        ])
      },
      range: ['online-device']
    }
  ]

  return staticColumns.filter((item) => {
    if (!item.range) {
      return true
    } else {
      if (item.range.includes(activeTab.value)) {
        return true
      }
      return false
    }
  })
})

const data = ref<LogRowData[]>([])
const pageInfo = reactive<IndexObj>({
  page: 1,
  pageSize: 50,
  type: 'user.login'
})

const pageResultInfo = reactive({
  pages: 0,
  total: 0
})
const loading = ref(false)

// 初始化page信息
const initPageInfo = () => {
  pageInfo.page = 1
  pageInfo.pageSize = 50
  pageResultInfo.pages = 0
  pageResultInfo.total = 0
}

// 加载用户的登录设备
const loadLoginDevices = () => {
  loading.value = true
  getLogDeviceByPage({
    page: pageInfo.page,
    pageSize: pageInfo.pageSize
  })
    .then((res) => {
      data.value = res.data.items
      pageResultInfo.pages = res.data.pages
      pageResultInfo.total = res.data.total
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

// 加载用户的登录日志
const loadLoginLogs = () => {
  loading.value = true
  getUserLogByPage({
    page: pageInfo.page,
    pageSize: pageInfo.pageSize,
    type: 'user.login'
  })
    .then((res) => {
      data.value = res.data.items
      pageResultInfo.pages = res.data.pages
      pageResultInfo.total = res.data.total
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

// 加载用户的在线设备
const loadOnLineDevices = () => {
  loading.value = true
  getLogDeviceByPage({
    page: pageInfo.page,
    pageSize: pageInfo.pageSize
  })
    .then((res) => {
      data.value = res.data.items
      pageResultInfo.pages = res.data.pages
      pageResultInfo.total = res.data.total
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

const loadData = () => {
  if (activeTab.value === 'login-device') {
    loadLoginDevices()
  } else if (activeTab.value === 'login-log') {
    loadLoginLogs()
  } else if (activeTab.value === 'online-device') {
    loadOnLineDevices()
  }
}

// 创建时间那一列的sort筛选排序发生变化
const handleSorterChange = (sorter: IndexObj) => {
  if (sorter && sorter.columnKey === 'createTime') {
    if (sorter.order === 'ascend') {
      data.value = data.value.sort((v1: LogRowData, v2: LogRowData) => {
        return dayjs(v1.createTime).valueOf() - dayjs(v2.createTime).valueOf()
      })
    } else {
      data.value = data.value.sort((v1: LogRowData, v2: LogRowData) => {
        return dayjs(v2.createTime).valueOf() - dayjs(v1.createTime).valueOf()
      })
    }
  }
}

const checkedRowKeys = ref<string[]>([])

const handlePageChange = (page?: number, pageSize?: number) => {
  page && (pageInfo.page = page)
  pageSize && (pageInfo.pageSize = pageSize)
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss"></style>
